using System;
using System.IO;
using System.Text;
using System.Runtime.InteropServices;

namespace csammisrun.OscarLib.Utility
{
	/// <summary>
	/// Provides static methods to log events and dump data
	/// </summary>
	internal class Logging
	{

		[DllImport("Kernel32.dll")]
		public static extern bool QueryPerformanceCounter(
			out long lpPerformanceCount);
		[DllImport("Kernel32.dll")]
		public static extern bool QueryPerformanceFrequency(
			out long lpPerformanceFreq);

		public static StreamWriter sw = null;

		public static void DumpFLAP(byte[] buffer, string message)
		{
      if (Logging.sw != null)
      {
        lock (Logging.sw)
        {
          Logging.sw.WriteLine(DateTime.Now.ToString() + " - " + message);
          int i, j = buffer.Length, k;

          StringBuilder sb = new StringBuilder();

          for (i = 0, k = 1; i < j; i++, k++)
          {
            Logging.sw.Write("{0:x2} ", buffer[i]);
            if (buffer[i] >= 0x20 && buffer[i] <= 0x7E)
              sb.Append((char)buffer[i]);
            else
              sb.Append(".");

            if ((k == 16))
            {
              Logging.sw.WriteLine(String.Format("\t{0}", sb.ToString()));
              sb.Remove(0, sb.Length);
              k = 0;
            }
          }

          Logging.sw.WriteLine(String.Format("\t{0}", sb.ToString()));
          Logging.sw.WriteLine("");
          Logging.sw.Flush();
        }
      }
		}

		public static void WriteString(string str)
		{
      if (Logging.sw != null)
      {
        lock (Logging.sw)
        {
          Logging.sw.WriteLine(DateTime.Now.ToString() + " - " + str);
          Logging.sw.WriteLine("");
          Logging.sw.Flush();
        }
      }
		}

    internal static void DumpDataPacket(DataPacket dp)
    {
      StringBuilder sb1 = new StringBuilder();
      sb1.AppendFormat(
        System.Globalization.CultureInfo.CurrentCulture.NumberFormat, "SNAC: ({0:x4},{1:x4}), flags = {2:x4}, requestID = {3:x8}"
              + Environ.NewLine + "FLAP: channel = {4:x1}, sequence = {5:x2}, datasize = {6:x2}",
        dp.SNAC.FamilyServiceID,
        dp.SNAC.FamilySubtypeID,
        dp.SNAC.Flags,
        dp.SNAC.RequestID,
        dp.FLAP.Channel,
        dp.FLAP.DatagramSequenceNumber,
        dp.FLAP.DataSize);
      Logging.DumpFLAP(dp.Data, sb1.ToString());
    }
  }
}
